package com.hmdp.interceptors;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.common.constant.SystemConstants;
import com.hmdp.core.service.impl.RedisServiceImpl;
import com.hmdp.entity.dto.UserDTO;
import com.hmdp.common.constant.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 计算机系 ITAEM 摆渡人
 * @description
 * @date 2022/10/16 14:57
 */
public class RFlashTokenInterceptor implements HandlerInterceptor {

    private RedisServiceImpl redisService;

    public RFlashTokenInterceptor(RedisServiceImpl redisService) {
        this.redisService = redisService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader(SystemConstants.TOKEN);
        if(StringUtils.isBlank(token)){
            return true;
        }
        //2.基于token获取用户
        String key = RedisConstants.LOGIN_USER_KEY + token;
        UserDTO userDTO = redisService.getHashObject(key, new UserDTO());
        //2.判断用户是否存在
        if(Objects.isNull(userDTO)){
            return true;
        }
        //3.存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        //4.刷新token有效期
        redisService.expire(key,30, TimeUnit.MINUTES);
        //5.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        //移除用户，防止内存泄露
        UserHolder.removeUser();
    }
}